//
//  HttpDNSController.m
//  WebSocketTest
//
//  Created by tanqilong on 16/9/5.
//  Copyright © 2016年 tanqilong. All rights reserved.
//

#import "HttpDNSController.h"
#import "AFNetworking.h"
#import "XLHttpNetworking.h"

@interface HttpDNSController () <NSURLSessionDelegate>
@property (nonatomic,strong) XLHttpNetworking * net;
@end

@implementation HttpDNSController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //获取ip
//    NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
//    AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    NSURL * url = [NSURL URLWithString:@"https://jin.caimao.com/api/content/gjs_notice_list"];
//    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
//    NSURLSessionDataTask * dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@",dic);
//    }];
//    [dataTask resume];
//
    
    
//    AFHTTPSessionManager * httpManager = [AFHTTPSessionManager manager];
//    AFHTTPRequestSerializer * requestS = [AFHTTPRequestSerializer serializer];
//    [requestS setValue:@"https://jin.caimao.com" forHTTPHeaderField:@"Host"];
//    NSLog(@"%@",requestS.HTTPRequestHeaders);
////    httpManager.securityPolicy.allowInvalidCertificates = YES;
//    
//    [httpManager GET:@"https://123.206.1.214/api/content/gjs_notice_list" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@",[responseObject class]);
//        
//        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"%@",dic);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@",requestS.HTTPRequestHeaders);
//        NSLog(@"%@",error);
//    }];
    
    //配置session
    NSURLSessionConfiguration * sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession * session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
    
    //配置地址
    NSURL *URL = [NSURL URLWithString:@"https://123.206.1.214/api/content/gjs_notice_list"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSLog(@"%@",request.URL.host);
    
    //发起请求
    NSURLSessionTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dic);
    }];
    [task resume];
    
}


//验证证书是否有效
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
                  forDomain:(NSString *)domain
{
    /*
     * 创建证书校验策略
     */
    NSMutableArray *policies = [NSMutableArray array];
    if (domain) {
        [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
    } else {
        [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
    }
    /*
     * 绑定校验策略到服务端的证书上
     */
    SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
    /*
     * 评估当前serverTrust是否可信任，
     * 官方建议在result = kSecTrustResultUnspecified 或 kSecTrustResultProceed
     * 的情况下serverTrust可以被验证通过，https://developer.apple.com/library/ios/technotes/tn2232/_index.html
     * 关于SecTrustResultType的详细信息请参考SecTrust.h
     */
    SecTrustResultType result;
    SecTrustEvaluate(serverTrust, &result);
    return (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
}


-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    if (!challenge) {
        return;
    }
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    NSURLCredential * credential = nil;
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([self evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:@"jin.caimao.com"]) {
            disposition = NSURLSessionAuthChallengeUseCredential;
            credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        }
        else {
            disposition = NSURLSessionAuthChallengePerformDefaultHandling;
        }
    }
    else {
         disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    }
    completionHandler(disposition,credential);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
